package com.zcloud.eventstudydemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcloud.eventstudydemo.dto.RestWebResponse;
import com.zcloud.eventstudydemo.entity.Term;
import com.zcloud.eventstudydemo.entity.TermBak;
import com.zcloud.eventstudydemo.mapper.TermMapper;
import com.zcloud.eventstudydemo.mapper.TermBakMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/terms")
public class TermController {

    @Autowired
    private TermMapper termMapper;
    
    @Autowired
    private TermBakMapper termBakMapper;

    /**
     * 分页查询词条列表
     * @param pageNum 页码，默认为1
     * @param pageSize 每页大小，默认为10
     * @param keyword 搜索关键词（可选）
     * @return 词条分页列表
     */
    @GetMapping("/list")
    public RestWebResponse<IPage<Term>> listTerms(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {

        // 创建分页对象
        IPage<Term> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        QueryWrapper<Term> wrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like("name", keyword).or().like("description", keyword);
        }
        wrapper.orderByDesc("create_time");

        // 执行分页查询
        IPage<Term> result = termMapper.selectPage(page, wrapper);
        return RestWebResponse.success(result);
    }

    /**
     * 新增词条
     * @param term 词条对象
     * @return 操作结果
     */
    @PostMapping("/add")
    public RestWebResponse<String> addTerm(@RequestBody Term term) {
        try {
            // 设置创建时间和更新时间
            term.setCreateTime(LocalDateTime.now());
            term.setUpdateTime(LocalDateTime.now());
            
            // 设置默认创建人
            if (term.getCreator() == null || term.getCreator().trim().isEmpty()) {
                term.setCreator("admin");
            }
            
            termMapper.insert(term);
            return RestWebResponse.success("词条添加成功");
        } catch (Exception e) {
            return new RestWebResponse<>("500", "词条添加失败: " + e.getMessage(), null);
        }
    }

    /**
     * 批量新增词条
     * @param termList 词条对象列表
     * @return 操作结果
     */
    @PostMapping("/addList")
    public RestWebResponse<String> addTermList(@RequestBody List<Term> termList) {
        try {
            int successCount = 0;
            int failCount = 0;
            
            // 遍历词条列表，逐个插入数据库
            for (Term term : termList) {
                try {
                    // 设置创建时间和更新时间
                    term.setCreateTime(LocalDateTime.now());
                    term.setUpdateTime(LocalDateTime.now());
                    
                    // 设置默认创建人
                    if (term.getCreator() == null || term.getCreator().trim().isEmpty()) {
                        term.setCreator("admin");
                    }
                    
                    // 插入数据库
                    termMapper.insert(term);
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    // 记录错误但继续处理其他数据
                }
            }
            
            // 返回结果
            String message = String.format("批量新增完成，成功：%d条，失败：%d条", successCount, failCount);
            if (failCount == 0) {
                return RestWebResponse.success(message);
            } else if (successCount > 0) {
                return new RestWebResponse<>("206", message, null); // 部分成功
            } else {
                return new RestWebResponse<>("500", "批量新增全部失败: ", null);
            }
        } catch (Exception e) {
            return new RestWebResponse<>("500", "批量新增失败: " + e.getMessage(), null);
        }
    }

    /**
     * 修改词条
     * @param term 词条对象
     * @return 操作结果
     */
    @PostMapping("/update")
    public RestWebResponse<String> updateTerm(@RequestBody Term term) {
        try {
            // 检查词条是否存在
            Term existingTerm = termMapper.selectById(term.getId());
            if (existingTerm == null) {
                return new RestWebResponse<>("404", "词条不存在", null);
            }

            // 设置更新时间
            term.setUpdateTime(LocalDateTime.now());
            
            // 执行更新操作
            termMapper.updateById(term);
            return RestWebResponse.success("词条更新成功");
        } catch (Exception e) {
            return new RestWebResponse<>("500", "词条更新失败: " + e.getMessage(), null);
        }
    }

    /**
     * 删除词条
     * @param id 词条ID
     * @return 操作结果
     */
    @GetMapping("/delete/{id}")
    public RestWebResponse<String> deleteTerm(@PathVariable Long id) {
        try {
            // 检查词条是否存在
            Term existingTerm = termMapper.selectById(id);
            if (existingTerm == null) {
                return new RestWebResponse<>("404", "词条不存在", null);
            }

            // 执行删除操作
            termMapper.deleteById(id);
            return RestWebResponse.success("词条删除成功");
        } catch (Exception e) {
            return new RestWebResponse<>("500", "词条删除失败: " + e.getMessage(), null);
        }
    }

    /**
     * 获取词条详情
     * @param id 词条ID
     * @return 词条详情
     */
    @GetMapping("/detail/{id}")
    public RestWebResponse<Term> getTermDetail(@PathVariable Long id) {
        try {
            Term term = termMapper.selectById(id);
            if (term == null) {
                return new RestWebResponse<>("404", "词条不存在", null);
            }
            return RestWebResponse.success(term);
        } catch (Exception e) {
            return new RestWebResponse<>("500", "获取词条详情失败: " + e.getMessage(), null);
        }
    }
    
    /**
     * 从term_bak表中随机查询8-36条数据并返回给前端，提示采集成功
     * @return 采集结果和数据列表
     */
    @GetMapping("/collect")
    public RestWebResponse<List<TermBak>> collectTerms() {
        try {
            // 随机生成8-36之间的数字
            Random random = new Random();
            int count = random.nextInt(29) + 8; // 生成8-36之间的随机数（包含8和36）
            
            // 创建查询条件，随机查询指定数量的数据
            QueryWrapper<TermBak> wrapper = new QueryWrapper<>();
            wrapper.last("ORDER BY RAND() LIMIT " + count); // MySQL随机排序并限制数量
            
            // 执行查询
            List<TermBak> termBakList = termBakMapper.selectList(wrapper);
            
            // 返回成功结果
            return new RestWebResponse<>("200", "采集成功，共采集到" + termBakList.size() + "条数据", termBakList);
        } catch (Exception e) {
            return new RestWebResponse<>("500", "采集失败: " + e.getMessage(), null);
        }
    }
    
    /**
     * 根据词条ID查询相关词条（知识图谱接口）
     * @param id 词条ID
     * @return 包含当前词条和相关词条的信息
     */
    @GetMapping("/graph/{id}")
    public RestWebResponse<TermGraph> getTermGraph(@PathVariable Long id) {
        try {
            // 查询主词条
            Term mainTerm = termMapper.selectById(id);
            if (mainTerm == null) {
                return new RestWebResponse<>("404", "词条不存在", null);
            }
            
            // 查询所有词条
            List<Term> allTerms = termMapper.selectList(new QueryWrapper<>());
            
            // 构建1级知识图谱
            List<Term> level1Terms = new ArrayList<>();
            for (Term term : allTerms) {
                // 排除主词条本身
                if (!term.getId().equals(id) && 
                    mainTerm.getDescription() != null && 
                    mainTerm.getDescription().contains(term.getName())) {
                    level1Terms.add(term);
                }
            }
            
            // 构建2级知识图谱
            Map<Long, List<Term>> level2TermsMap = new HashMap<>();
            for (Term level1Term : level1Terms) {
                List<Term> level2Terms = new ArrayList<>();
                for (Term term : allTerms) {
                    // 排除主词条和1级词条本身
                    if (!term.getId().equals(id) && 
                        !term.getId().equals(level1Term.getId()) &&
                        level1Term.getDescription() != null && 
                        level1Term.getDescription().contains(term.getName())) {
                        level2Terms.add(term);
                    }
                }
                level2TermsMap.put(level1Term.getId(), level2Terms);
            }
            
            // 创建图谱对象
            TermGraph termGraph = new TermGraph();
            termGraph.setMainTerm(mainTerm);
            termGraph.setLevel1Terms(level1Terms);
            termGraph.setLevel2TermsMap(level2TermsMap);
            
            return RestWebResponse.success(termGraph);
        } catch (Exception e) {
            return new RestWebResponse<>("500", "查询词条图谱失败: " + e.getMessage(), null);
        }
    }
    
    /**
     * 词条图谱数据结构
     */
    public static class TermGraph {
        /**
         * 主词条
         */
        private Term mainTerm;
        
        /**
         * 1级相关词条列表
         */
        private List<Term> level1Terms;
        
        /**
         * 2级相关词条映射，key为1级词条ID，value为对应的2级词条列表
         */
        private Map<Long, List<Term>> level2TermsMap;
        
        public Term getMainTerm() {
            return mainTerm;
        }
        
        public void setMainTerm(Term mainTerm) {
            this.mainTerm = mainTerm;
        }
        
        public List<Term> getLevel1Terms() {
            return level1Terms;
        }
        
        public void setLevel1Terms(List<Term> level1Terms) {
            this.level1Terms = level1Terms;
        }
        
        public Map<Long, List<Term>> getLevel2TermsMap() {
            return level2TermsMap;
        }
        
        public void setLevel2TermsMap(Map<Long, List<Term>> level2TermsMap) {
            this.level2TermsMap = level2TermsMap;
        }
    }
}